<template>
  <FormModal
    title="json"
    width="900px"
    v-model:modelValue="modalVisible"
    keyboard
    maskClosable
  >
    <div class="code-wrapper">
      <a-textarea
        id="code-textarea"
        ref="textareaRef"
        v-model:value="codeStr"
        style="height: 100%"
        autofocus="autofocus"
        @keyup.enter="handleOk"
      ></a-textarea>
    </div>
    <template #footer>
      <a-button @click="handleClose"> 取消 </a-button>
      <a-button
        type="primary"
        style="margin-left: 25px"
        :loading="submitLoading"
        @click="handleOk"
      >
        解析
      </a-button>
    </template>
  </FormModal>
</template>

<script>
import FormModal from "@/components/FormModal/index.vue";
import { fieldFactory } from "@/views/FormGenerator/util";

const typeMap = {
  string: "input",
  number: "input-number",
};

export default {
  components: {
    FormModal,
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return { submitLoading: false, codeStr: "" };
  },
  computed: {
    modalVisible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit("update:modelValue", val);
      },
    },
  },
  watch: {
    modelValue() {
      if (this.modelValue) {
        this.$nextTick(() => {
          this.$refs.textareaRef?.focus();
        });
      }
    },
  },
  methods: {
    handleClose() {
      this.codeStr = "";
      this.submitLoading = false;
      this.modalVisible = false;
    },
    handleOk() {
      try {
        if (!this.codeStr) return;
        this.submitLoading = true;
        setTimeout(() => {
          const codeObj = JSON.parse(this.codeStr);
          const properties = codeObj.properties;
          if (!properties) throw new Error("代码格式错误");
          const result = [];
          for (const key of Object.keys(properties)) {
            const detail = properties[key];
            result.push(
              fieldFactory(
                typeMap[detail.type] ?? "input",
                detail.description,
                key
              )
            );
          }
          this.$emit("resolveJson", result);
          this.handleClose();
        }, 100);
      } catch (e) {
        this.$message.warn("数据格式错误");
      }
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.ant-modal-body) {
  padding: 0 !important;
}
.code-wrapper {
  height: 500px;
}
</style>
